package threadUtils.demo06;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock显示锁的应用，确保获取锁的释放
 * 可重入性.如果，多次获取锁之后没有对锁进行依次释放，那么就会造成线程阻塞，而且在主线程结束之后，就成了死锁
 */
public class LockExample {

    public static void main(String[] args) throws InterruptedException {

        final ReentrantLock lock = new ReentrantLock();

        new Thread(() -> {
            lock.lock();
            try {
                System.out.println(Thread.currentThread().getName() + " acquired the lock");
                assert  lock.getHoldCount() == 1;
                lock.lock();
                System.out.println(Thread.currentThread().getName() + " acquired the lock again . ");
                assert lock.getHoldCount() == 2;
            } finally {
                lock.unlock();
                System.out.println(Thread.currentThread().getName() + " unlock ");
                assert lock.getHoldCount() == 1;
            }
        }).start();
        TimeUnit.SECONDS.sleep(2);
        lock.lock();
        System.out.println("main thread acquired the lock");
        lock.unlock();
        System.out.println("main thread released the lock");

    }
}
